//
//  DetailFact_VC.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 22.11.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "DetailFact_VC.h"
#import "DataBase.h"
#import "FactPage.h"
#import "Service.h"
#import "Comments_VC.h"
#import "ShareMenager.h"
#import "UIImageView+WebCache.h"

@implementation DetailFact_VC

@synthesize fact_id,fact_number,category_id,fact_type,fact_mode,factIds;

#pragma mark - init

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        
        titleView.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f]; // Change to desired color
        
        self.navigationItem.titleView = titleView;
    }
    
    titleView.text = title;
    [titleView sizeToFit];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

#pragma mark - View Life

- (void)viewDidLoad{
    [super viewDidLoad];
    [self setNavTitle:@"Мир фактов"];
    [self setupBackButton];
    [self showHUD];
    [self registerNotifications];
    [self performSelector:@selector(prepare) withObject:nil afterDelay:0.5f];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    bottomMenu.alpha = 0.0f;
    shareMenu.alpha = 0.0f;
}


-(void)prepare{ 
    if(fact_mode==1)
        factIds = [[DataBase sharedManeger] getFactsIds:category_id fromFact_id:0 factType:fact_type];
    else if(fact_mode==2)
        factIds = [[DataBase sharedManeger] getFactsIdsFavorites];

    
    [self addBottomMenu];
    [self setupFavoriteButton];
    [self setFavoriteButton]; 
    
    self.pagingView.horizontal = TRUE;
    self.pagingView.currentPageIndex = fact_number;
    [self currentPageDidChangeInPagingView:self.pagingView];
    [self.pagingView reloadData];
    
    [self hideHUD];
    
    [self setRead];
}

-(void)setupBackButton{
    self.navigationItem.leftBarButtonItem = nil;
    
    UIButton *back_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [back_btn setFrame:CGRectMake(0, 0, 62, 34)];
    [back_btn setBackgroundImage:[UIImage imageNamed:@"back-btn"] forState:UIControlStateNormal];
    [back_btn setBackgroundImage:[UIImage imageNamed:@"back-btn1"] forState:UIControlStateHighlighted];
    [back_btn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:back_btn];
}

-(void)setupFavoriteButton{
    favoriteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 31, 31)];
    [favoriteButton setBackgroundImage:[UIImage imageNamed:@"1352843635_keditbookmarks.png"] forState:UIControlStateSelected];
    [favoriteButton setBackgroundImage:[UIImage imageNamed:@"1352843635_keditbookmarks_selected.png"] forState:UIControlStateNormal];
    [favoriteButton addTarget:self action:@selector(onFavorite:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:favoriteButton];
}

#pragma mark - content

-(void)setFavoriteButton{
    favoriteButton.selected = [[fact valueForKey:@"is_favorite"] boolValue];
}

-(void)setRead{
    if([[fact valueForKey:@"is_read"] intValue]==0){
        [[DataBase sharedManeger] setReadToFact:[[fact valueForKey:@"fact_id"] intValue]];        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SET_READ" object:[NSNumber numberWithInt:fact_number] userInfo:nil];
    }
}

-(void)setBottomMenuContent{    
    [bottomMenu loading:YES];
    
    bottomMenu.commentsCountlabel.text = @"0";
    bottomMenu.likeCountLabel.text = @"0";
    bottomMenu.likeButton.selected = FALSE;
    
    if([[fact valueForKey:@"update"] intValue]==0){
        bottom_fact_id = [[fact valueForKey:@"fact_id"] intValue];
        [self performSelector:@selector(getFactInfo:) withObject:[NSNumber numberWithInt:bottom_fact_id] afterDelay:0.3f];
    }
    else {
        [bottomMenu loading:FALSE];

        bottomMenu.commentsCountlabel.text = [NSString stringWithFormat:@"%@",[fact valueForKey:@"number_of_comments"]];
        bottomMenu.likeCountLabel.text = [NSString stringWithFormat:@"%@",[fact valueForKey:@"number_of_likes"]];
        bottomMenu.likeButton.selected = [[fact valueForKey:@"is_like"] intValue];
    }
}

-(void)getFactInfo:(NSNumber*)b_id{
    if(b_id.intValue!=[[fact valueForKey:@"fact_id"] intValue])
        return;
    
    [[Service sharedManeger] getFactInfo:[[fact valueForKey:@"fact_id"] intValue] withHandler:^(NSData *response, NSError *error) {
        [bottomMenu loading:FALSE];
        
        if(response){
            NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:[response objectFromJSONData]];
            
            int number_of_likes =  [[info valueForKey:@"number_of_likes"] intValue];
            int number_of_comments =  [[info valueForKey:@"number_of_comments"] intValue];
            int is_like =  [[info valueForKey:@"is_like"] intValue];
            int f_id =  [[info valueForKey:@"fact_id"] intValue];
            
            [[DataBase sharedManeger] updateFactInfo:f_id likes:number_of_likes comments:number_of_comments isLike:is_like];                
            
            if([[fact valueForKey:@"fact_id"] intValue]==f_id){
                bottomMenu.commentsCountlabel.text = [NSString stringWithFormat:@"%@",[info valueForKey:@"number_of_comments"]];
                bottomMenu.likeCountLabel.text = [NSString stringWithFormat:@"%@",[info valueForKey:@"number_of_likes"]];
                bottomMenu.likeButton.selected = [[info valueForKey:@"is_like"] intValue];  
                
                [fact setValue:[NSString stringWithFormat:@"%d",number_of_likes] forKey:@"number_of_likes"];
                [fact setValue:[NSString stringWithFormat:@"%d",number_of_comments] forKey:@"number_of_comments"];
                [fact setValue:[NSString stringWithFormat:@"%d",is_like] forKey:@"is_like"];
            }
        }
        else{
            bottomMenu.commentsCountlabel.text = [NSString stringWithFormat:@"%@",[fact valueForKey:@"number_of_comments"]];
            bottomMenu.likeCountLabel.text = [NSString stringWithFormat:@"%@",[fact valueForKey:@"number_of_likes"]];
            bottomMenu.likeButton.selected = [[fact valueForKey:@"is_like"] intValue];
        }
    }];
}

#pragma mark - database

-(void)getFact{
    fact = nil;
    fact = [[NSMutableDictionary alloc] initWithDictionary:[[DataBase sharedManeger]getFact:fact_id]];
}

#pragma mark - IBActions

-(void)onBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onFavorite:(UIButton*)sender{
    sender.selected = !sender.selected;
    
    [[DataBase sharedManeger] updateFavorites:[[fact valueForKey:@"fact_id"]intValue] is_Favorite:sender.selected];
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];    
    [info setValue:[NSNumber numberWithInt:fact_number] forKey:@"fact_number"];
    [info setValue:[NSNumber numberWithBool:sender.selected] forKey:@"is_favorite"];
    [info setValue:[fact valueForKey:@"fact_id"] forKey:@"fact_id"];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_FAVORITES" object:info userInfo:nil];
}

#pragma mark - Bottom Actions

-(IBAction)onLike:(UIButton*)sender{
    [self showHUD];
    
    BOOL selected = !sender.selected;
    
    int f_id = [[fact valueForKey:@"fact_id"] intValue];

    [[Service sharedManeger] addLike:f_id isLike:selected withHandler:^(NSData *response, NSError *error) {
        [self hideHUD];
        
        if(error){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message: [error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            return ;
        }
        
        sender.selected = selected;

        int likes = [[fact valueForKey:@"number_of_likes"]intValue];
        int is_like = 0;
        
        if(selected){
            likes++;
            is_like = 1;
        }
        else{
            likes--;
        }
        
        [fact setValue:[NSString stringWithFormat:@"%d",likes] forKey:@"number_of_likes"];
        
        [[DataBase sharedManeger] updateLikes:[[fact valueForKey:@"fact_id"] intValue] likes:likes is_like:is_like];
        
        bottomMenu.likeCountLabel.text = [NSString stringWithFormat:@"%d",likes];  
        
        NSMutableDictionary *info = [NSMutableDictionary dictionary];
        [info setValue:[NSString stringWithFormat:@"%d",likes]  forKey:@"likes"];
        [info setValue:[NSString stringWithFormat:@"%d",fact_number]  forKey:@"f_number"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_TOP" object:info];
        
    }];
  
}

-(IBAction)onComment:(UIButton*)sender{
    Comments_VC *vc = [[Comments_VC alloc] initWithNibName:@"Comments_VC" bundle:nil];
    vc.fact_id = [[fact valueForKey:@"fact_id"] intValue];
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)onShare:(UIButton*)sender{
    if(bottomMenu.alpha==1.0f){
        isShare = TRUE;
        
        [UIView transitionWithView:bottomMenu
                          duration:0.5 
                           options:UIViewAnimationOptionTransitionFlipFromTop
                        animations:^{
                            [bottomMenu setAlpha:0];
                        }
                        completion:^(BOOL finished){
                            [UIView animateWithDuration:0.1f delay:0.05f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                                [shareMenu setAlpha:1.0f];
                            } completion:^(BOOL finished) {
                                
                            }];
                        }
         ];
    }
    else{
        isShare = FALSE;

        [UIView transitionWithView:shareMenu
                          duration:0.5 
                           options:UIViewAnimationOptionTransitionFlipFromBottom
                        animations:^{
                            [shareMenu setAlpha:0];
                        }
                        completion:^(BOOL finished){
                            [UIView animateWithDuration:0.1f delay:0.05f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                                [bottomMenu setAlpha:1.0f];
                            } completion:^(BOOL finished) {
                                
                            }];
                        }
         ]; 
    }

    
}

#pragma mark - ATPagingViewDelegate methods

- (NSInteger)numberOfPagesInPagingView:(ATPagingView *)pagingView {
    return factIds.count;
}

- (UIView *)viewForPageInPagingView:(ATPagingView *)pagingView atIndex:(NSInteger)index {
    FactPage *view = (FactPage*)[pagingView dequeueReusablePage];
    if (view == nil) {
        view = [[FactPage alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
    }
        
    [view setContent:[[DataBase sharedManeger]getFact:[[factIds objectAtIndex:index] intValue]]];

    return view;
}


- (void)currentPageDidChangeInPagingView:(ATPagingView *)pagingView {
    fact_id = [[factIds objectAtIndex:pagingView.currentPageIndex] intValue];
    fact_number = pagingView.currentPageIndex;
        
    [self getFact];
    [self setFavoriteButton];
    [self setBottomMenuContent];
}


- (void)pagingViewWillBeginMoving:(ATPagingView *)pagingView{
}

- (void)pagingViewDidEndMoving:(ATPagingView *)pagingView{
    [self setRead];
}

#pragma mark - Bottom Menu

-(void)addBottomMenu{
    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"FactBottomMenu" owner:self options:nil];
    bottomMenu = [nibObjects objectAtIndex:0];
    
    CGRect frame = bottomMenu.frame;
    frame.origin.y = [[UIScreen mainScreen] bounds].size.height-frame.size.height;
                      
    bottomMenu.frame = frame;
            
    [[[[UIApplication sharedApplication] windows] lastObject] addSubview:bottomMenu];
    
    shareMenu = [nibObjects objectAtIndex:1];
    shareMenu.frame = frame;
    shareMenu.alpha = 0.0f;
    
    [[[[UIApplication sharedApplication] windows] lastObject] addSubview:shareMenu];
}



#pragma mark - Notifications

-(void)registerNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ON_PHOTO_CLICKED:) name:@"ON_PHOTO_CLICKED" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ON_PHOTOBROWSER_DONE:) name:@"ON_PHOTOBROWSER_DONE" object:nil];
}

-(void)removeNotifications{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ON_PHOTO_CLICKED" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ON_PHOTOBROWSER_DONE" object:nil];
}

-(void)ON_PHOTO_CLICKED:(NSNotification*)notif{
    int tag = [notif.object intValue] - 50;
        
    photos = nil;
    photos = [[NSMutableArray alloc] init];
    
    NSMutableArray *images = [fact objectForKey:@"images"];
    
    for (int i=0; i<images.count; i++) {
        MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:[images objectAtIndex:i]]];
        [photos addObject:photo];
    }

    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    [browser setDisplayActionButton:YES];
    [browser setInitialPageIndex:tag];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

-(void)ON_PHOTOBROWSER_DONE:(NSNotification*)notif{
    [self setupBackButton];

    [UIView animateWithDuration:0.0 
                          delay:0.15f 
                        options:UIViewAnimationCurveEaseInOut 
                     animations:^ {
                         if(!isShare)
                             bottomMenu.alpha = 1.0f;
                         else
                             shareMenu.alpha = 1.0f;
                     } 
                     completion:^(BOOL finished) {
                     }];
}

#pragma mark - photos browser

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count)
        return [photos objectAtIndex:index];
    return nil;
}

#pragma mark - loading

-(void)showHUD{
    hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    hud.dimBackground = YES;
    hud.tag = 20;
    [hud show:YES];
    [[[UIApplication sharedApplication]keyWindow] addSubview:hud];
}

-(void)hideHUD{
    [hud show:FALSE];
    [hud removeFromSuperview];
	hud = nil;
}

#pragma mark - Share

-(IBAction)onFacebook:(UIButton*)sender{
    [self showHUD];
    
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){        
        [[ShareMenager sharedManeger] postFBFact:fact fromViewController:self withCompletionHandler:^(BOOL isOK) {
            if(isOK){
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/Checkmark.png"]];
                hud.mode = MBProgressHUDModeCustomView;
                
                [self performSelector:@selector(hideHUD) withObject:nil afterDelay:1.0f];  
            }
            else{
                [self hideHUD];
            }
        }];
    });
}

-(IBAction)onVkontakte:(UIButton*)sender{
    [self showHUD];
        
    double delayInSeconds = 2.0;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ON_PHOTOBROWSER_DONE" object:nil];

        [[ShareMenager sharedManeger] postVKFact:fact fromViewController:self withCompletionHandler:^(BOOL isOK) {
            if(isOK){
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/Checkmark.png"]];
                hud.mode = MBProgressHUDModeCustomView;
                
                [self performSelector:@selector(hideHUD) withObject:nil afterDelay:1.0f];  
            }
            else{
                [self hideHUD];
            }
        }];
    });   
}

-(IBAction)onEmail:(UIButton*)sender{
	Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil){
		if ([mailClass canSendMail]){
			[self displayComposerSheet];
		}
		else{
			[self launchMailAppOnDevice];
		}
	}
	else{
		[self launchMailAppOnDevice];
	}

}

-(IBAction)onOther:(UIButton*)sender{
    [self showHUD];
    
    double delayInSeconds = 1.0;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        NSString *copyString = [[NSString alloc] initWithFormat:@"%@",[fact valueForKey:@"full_description"]];
        UIPasteboard *pb = [UIPasteboard generalPasteboard];
        [pb setString:copyString];
        
        hud.labelText = @"Текст скопирован";
        hud.mode = MBProgressHUDModeCustomView;
        [hud hide:YES afterDelay:1.5];
        
    }); 
}


#pragma mark - Compose Mail

-(void)displayComposerSheet {
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"Интересные факты"];
	
    NSMutableArray *imgs = [fact objectForKey:@"images"];
    
    UIImageView *avatar_view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, 32, 32)];
    
    [avatar_view setImageWithURL:[NSURL URLWithString:[imgs objectAtIndex:0]] placeholderImage:nil options:0 success:^(UIImage *image, BOOL cached) {
        [picker addAttachmentData:UIImageJPEGRepresentation(image, 0.8f) mimeType:@"image/jpeg" fileName:[NSString stringWithFormat:@"image1.jpg"]];
        
        NSString *emailBody = [fact valueForKey:@"full_description"];
        [picker setMessageBody:emailBody isHTML:NO];
        
        [self presentModalViewController:picker animated:YES];

    } failure:^(NSError *error) {        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:@"Изображение не загружено" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }];	
}


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {	
	[self dismissModalViewControllerAnimated:YES];
    
    [self setupBackButton];
    
    [UIView animateWithDuration:0.0 
                          delay:0.15f 
                        options:UIViewAnimationCurveEaseInOut 
                     animations:^ {
                         if(!isShare)
                             bottomMenu.alpha = 1.0f;
                         else
                             shareMenu.alpha = 1.0f;
                     } 
                     completion:^(BOOL finished) {
                     }];
}


-(void)launchMailAppOnDevice{
	NSString *recipients = @"subject=Интересные факты";
	NSString *body = [NSString stringWithFormat:@"&body=%@",[fact valueForKey:@"full_description"]];
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}


#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    [bottomMenu removeFromSuperview];
    [shareMenu removeFromSuperview];
    shareMenu = nil;
    favoriteButton = nil;
    fact = nil;
    factIds = nil;
    bottomMenu = nil;
}

@end
